/*********************************************************************************
 *      Copyright:  (C) 2022 zengwen<1825984037@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  get_massage.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/07/22)
 *         Author:  zengwen <1825984037@qq.com>
 *      ChangeLog:  1, Release initial version on "07/07/22 14:22:17"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "logger.h"

/*get temperature and the id of raspberrypi*/
int get_temper_ID (char tpid[] )
{
	float           temp;
	char            ID[128];
	DIR            *dirp=NULL;
	struct dirent  *redir=NULL;
	int             found=0;
	char            buf[128];
	char            path[128]="/sys/bus/w1/devices/";
	int             fd;
	char           *ptr=NULL;

	dirp=opendir(path);
	if(!dirp)
	{
		log_err ("open file %s failure:%s\n",path,strerror(errno));
		return -1;
	}
	log_info("open file %s successfully\n",path);

	while(NULL!=(redir=readdir(dirp)))
	{
		if(strstr(redir->d_name,"28-"))
		{
			strncpy(ID,redir->d_name,sizeof(ID));
			found=1;
		}
	}

	closedir(dirp);
	if(!found)
	{
		 log_err ("can not find this dirent:%s\n",strerror(errno));
		 return -2;
	}

	strncat(path,ID,sizeof(path)-strlen(path));
	strncat(path,"/w1_slave",sizeof(path)-strlen(path));
	log_info ("PATH=%s\n",path);

	if((fd=open(path,O_RDONLY))<0)
	{
		log_err ("open fd=%d failure:%s\n",fd,strerror(errno));
		return -3;
	}

	memset(buf,0,sizeof(buf));
	if((read(fd,buf,sizeof(buf)))<0)
	{
		log_err ("read fd=%d failure:%s\n",fd,strerror(errno));
		return -4;
	}

	ptr=strstr(buf,"t=");
	if(ptr==NULL)
	{
		log_err ("can not find t= string\n");
		return -5;
	}

	ptr+=2;
	temp=atof(ptr)/1000;
	snprintf(tpid,128,"%s/%f",ID,temp);

	close(fd);
	return 0;

}

/*get time*/
int get_time(char cur_time[])
{
	time_t timep;
	struct tm *p;

	time(&timep);
	p = gmtime(&timep);
	snprintf(cur_time, 20, "%d.%d.%d %d:%d:%d", 1900 + p->tm_year, 1 + p->tm_mon, p->tm_mday, 8 + p->tm_hour, p->tm_min, p->tm_sec);
	return 0;
}
